package org.csu.secondhand.api.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.csu.secondhand.api.entity.Cart;
import org.csu.secondhand.api.entity.Dealing;
import org.csu.secondhand.api.persistence.CartMapper;
import org.csu.secondhand.api.persistence.DealingMapper;
import org.csu.secondhand.api.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("cartService")
public class CartServiceImpl implements CartService {
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private DealingMapper dealingMapper;

    @Override
    public List<Dealing> getCartByUser(String user) {
        QueryWrapper<Cart> queryWrapper = new QueryWrapper();
        queryWrapper.eq("username", user);
        List<Cart> cartList = cartMapper.selectList(queryWrapper);
        List<Dealing> dealingList = new ArrayList<>();
        for(int i=0;i<cartList.size();i++) {
            Dealing dealing = dealingMapper.selectById(cartList.get(i).getDealing());
            dealingList.add(dealing);
        }
        return dealingList;
    }

    @Override
    public Cart insertCart(Cart cart) {
        cartMapper.insert(cart);
        return cart;
    }

    @Override
    public Cart removeCart(String user, long dealing) {
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user).eq("dealing", dealing);
        Cart cart = cartMapper.selectOne(queryWrapper);
        cartMapper.delete(queryWrapper);
        return cart;
    }

    @Override
    public int isInCart(String user, long dealing) {
        QueryWrapper<Cart> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", user).eq("dealing", dealing);
        Cart cart = cartMapper.selectOne(queryWrapper);
        if(cart == null)
            return 0;
        return 1;
    }
}
